<template>
  <div>
    <!-- 视频播放层 -->
    <div v-if="!videoEnded" class="video-fullscreen-container">
      <video
        ref="videoPlayer"
        class="full-screen-video"
        @ended="handleVideoEnd"
        autoplay
      >
        <source src="/偏铝酸钠.webm" type="video/webm">
      </video>
      <div class="skip-hint">
        按 ESC 键跳过视频
      </div>
    </div>

    <!-- 个人中心内容 -->
    <div v-show="videoEnded" class="profile-container">
      <el-row :gutter="20" class="profile-row">
        <!-- 左侧导航 - 固定宽度 -->
        <el-col :span="4" class="left-nav">
          <el-menu
            :default-active="activeTab"
            class="profile-menu"
            @select="handleMenuSelect"
          >
            <el-menu-item index="basic">
              <el-icon><User /></el-icon>
              <span>基本信息</span>
            </el-menu-item>
            <el-menu-item index="detail">
              <el-icon><Document /></el-icon>
              <span>个人信息</span>
            </el-menu-item>
            <el-menu-item index="security">
              <el-icon><Lock /></el-icon>
              <span>安全设置</span>
            </el-menu-item>
            <el-menu-item index="collection">
              <el-icon><Star /></el-icon>
              <span>我的收藏</span>
            </el-menu-item>
            <el-menu-item index="setting">
              <el-icon><Setting /></el-icon>
              <span>用户设置</span>
            </el-menu-item>
            <!-- 新增的粉丝与关注列表 -->
            <el-menu-item index="follow">
              <el-icon><Connection /></el-icon>
              <span>粉丝与关注</span>
            </el-menu-item>
          </el-menu>
        </el-col>

        <!-- 右侧内容区 - 可滚动 -->
        <el-col :span="20" class="right-content">
          <div class="profile-content">
            <!-- 各组件内容保持不变 -->
            <BasicInfo
              v-if="activeTab === 'basic'"
              :user="userData"
              :loading="loading"
            />
            <DetailInfo
              v-if="activeTab === 'detail'"
              :user="userData"
              :loading="loading"
              @update="handleUpdateUser"
            />
            <SecuritySettings
              v-if="activeTab === 'security'"
              :password="userData.password"
              :phone="userData.phone"
              @password-change="handlePasswordChange"
            />
            <CollectionList
              v-if="activeTab === 'collection'"
              :id="userData.id"
              :loading="loading"
            />
            <UserSetting
                v-if="activeTab === 'setting'"
                :user="userData"
                :loading="loading"
            />
            <!-- 新增的粉丝与关注组件 -->
            <FollowList
              v-if="activeTab === 'follow'"
              :id="userData.id"
              :loading="loading"
            />
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>


<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { User, Document, Lock, Star,Connection  } from '@element-plus/icons-vue'
import BasicInfo from './personal/BasicInfo.vue'
import DetailInfo from './personal/DetailInfo.vue'
import SecuritySettings from './personal/SecuritySettings.vue'
import CollectionList from './personal/CollectionList.vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useUserStore } from '@/store/user'
import UserSetting from "./personal/UserSetting.vue";
import FollowList from './personal/FollowList.vue' // 你需要创建这个组件
import img from '@/assets/images/doro.jpg'
const userStore = useUserStore()
const activeTab = ref('basic')
const loading = ref(false)
const videoPlayer = ref(null)
const videoEnded = ref(false)
const topNav = ref(null)

// 检查视频是否已播放过
const hasVideoPlayed = localStorage.getItem('hasWatchedIntroVideo')

// 更新获取和设置导航栏显示状态的函数
const updateNavVisibility = (show) => {
  // 确保每次都重新获取导航栏元素
  topNav.value = document.querySelector('.top-nav')
  if (topNav.value) {
    topNav.value.style.display = show ? 'block' : 'none'
  }
  document.body.style.overflow = show ? 'auto' : 'hidden'
}

if (hasVideoPlayed) {
  videoEnded.value = true
  // 确保TopNav显示
  updateNavVisibility(true)
} else {
  // 没有播放过，则隐藏导航
  updateNavVisibility(false)
}

// 用户数据
const userData = ref({
  id: null,
  userName: '',
  email: '',
  userType: null,
  followeeId: null,
  followerId: null,
  gender: null,
  age: null,
  bio: '',
  phone: '',
  password: '',
  avatar: img
})

// 获取用户数据
const fetchUserData = async () => {
  if (!userStore.userInfo.id) {
    ElMessage.error('用户未登录')
    return
  }

  loading.value = true
  try {
    const response = await axios.get('/api/auth/personalCenter', {
      params: {
        id: userStore.userInfo.id
      }
    })

    if (response.data.code === 200) {
      userData.value = {
        ...userData.value,
        ...response.data.data,
      }
      console.log('用户数据:', userData.value)
    } else {
      ElMessage.error(response.data.message || '获取用户信息失败')
    }
  } catch (error) {
    ElMessage.error('获取用户信息失败')
    console.error('Error fetching user data:', error)
  } finally {
    loading.value = false
  }
}

// 更新用户信息
// 更新用户信息（强制创建新对象保证响应式）
const handleUpdateUser = async (updatedData) => {
  loading.value = true;
  try {
    const response = await axios.post('/api/auth/updateProfile', {
      ...updatedData,
      id: userData.value.id
    });

    // 关键修改：创建全新对象并替换
    userData.value = {
      ...JSON.parse(JSON.stringify(userData.value)), // 深拷贝当前值
      ...updatedData // 覆盖更新字段
    };

    ElMessage.success('更新成功');

    // 如果需要重新获取数据（保守方案）
    // await fetchUserData();
  } catch (error) {
    // 即使请求失败也强制更新本地数据
    userData.value = { ...userData.value, ...updatedData };
    ElMessage.warning('数据已本地更新，但服务器响应异常');
  } finally {
    loading.value = false;
  }
}

const handleMenuSelect = (index) => {
  activeTab.value = index
}

const handlePasswordChange = () => {
  ElMessage.success('密码修改成功，请重新登录')
  // 这里可以添加跳转到登录页的逻辑
}

const handleVideoEnd = () => {
  if (videoPlayer.value) {
    videoPlayer.value.pause()
    videoPlayer.value.currentTime = 0
  }
  videoEnded.value = true
  
  // 设置 localStorage 标记
  localStorage.setItem('hasWatchedIntroVideo', 'true')

  // 使用新的函数显示导航
  updateNavVisibility(true)
}

// 添加 ESC 键监听函数
const handleKeyPress = (event) => {
  if (event.key === 'Escape' && !videoEnded.value) {
    handleVideoEnd()
  }
}

onMounted(() => {
  // 添加 ESC 键监听
  window.addEventListener('keydown', handleKeyPress)

  // 只有在视频未播放过的情况下才隐藏顶部导航栏
  if (!hasVideoPlayed) {
    updateNavVisibility(false)
  }

  // 视频加载完成后自动播放
  if (videoPlayer.value) {
    videoPlayer.value.play().then(() => {
      // 不再调用 requestFullscreen，而是使用 CSS 实现全屏效果
    }).catch((err) => {
      console.log('视频播放失败:', err)
      videoEnded.value = true
      // 恢复顶部导航显示
      updateNavVisibility(true)
    })
  }

  fetchUserData()
})

// 组件卸载时确保恢复正常显示
onUnmounted(() => {
  // 移除 ESC 键监听
  window.removeEventListener('keydown', handleKeyPress)
  updateNavVisibility(true)
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  overflow: hidden; /* 防止整个页面滚动 */
}

.profile-row {
  display: flex;
  height: 100%;
}

/* 左侧导航固定样式 */
.left-nav {
  position: fixed;
  width: 16.6667%; /* el-col span=4 对应的宽度 */
  height: calc(100vh - 100px); /* 减去顶部和底部间距 */
  overflow-y: auto; /* 如果导航内容很多也可以滚动 */
}

.profile-menu {
  border-radius: 4px;
  height: 100%;
}

/* 右侧内容可滚动样式 */
.right-content {
  margin-left: 16.6667%; /* 与左侧导航宽度一致 */
  width: 83.3333%; /* el-col span=20 对应的宽度 */
}

.profile-content {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  min-height: 600px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: calc(100vh - 100px); /* 减去顶部和底部间距 */
  overflow-y: auto; /* 启用垂直滚动 */
}

/* 响应式调整 */
@media (max-width: 992px) {
  .left-nav {
    width: 200px; /* 小屏幕固定宽度 */
  }
  .right-content {
    margin-left: 200px;
    width: calc(100% - 200px);
  }
}

@media (max-width: 768px) {
  .profile-row {
    flex-direction: column;
  }

  .left-nav {
    position: static;
    width: 100%;
    height: auto;
  }
  .right-content {
    margin-left: 0;
    width: 100%;
  }
}

.video-fullscreen-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: black;
  z-index: 99999; /* 确保视频容器在最顶层 */
}

.full-screen-video {
  width: 100%;
  height: 100%;
  object-fit: contain;
  display: block;
}

.skip-hint {
  position: fixed;
  bottom: 20px;
  right: 20px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 10px 20px;
  border-radius: 4px;
  font-size: 14px;
  z-index: 100000;
}

/* 左侧导航栏 - 浪花动态背景 */
.left-nav {
  position: fixed;
  width: 16.6667%;
  height: calc(100vh - 100px);
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  z-index: 10;
  transition: all 0.3s ease;
}

.left-nav::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background:
    url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill='%23a8d0ff' fill-opacity='0.2' d='M45,-65.1C57.6,-55.4,66.3,-39.6,72.3,-22.2C78.3,-4.8,81.6,14.2,75.3,29.9C69,45.6,53.1,58.1,35.4,68.7C17.7,79.3,-1.8,88.1,-19.6,83.9C-37.4,79.8,-53.5,62.8,-64.1,43.5C-74.7,24.2,-79.8,2.7,-75.7,-16.1C-71.6,-34.9,-58.3,-51.1,-42.4,-60.1C-26.5,-69.1,-8,-70.9,9.3,-78.6C26.6,-86.3,53.2,-99.9,65.1,-91.1C77,-82.3,74.2,-51.1,72.5,-25.7C70.8,-0.3,70.3,19.3,63.5,35.2C56.7,51.1,43.7,63.3,28.7,71.6C13.7,79.9,-3.3,84.3,-20.8,81.3C-38.3,78.3,-56.3,67.9,-67.2,51.6C-78.1,35.3,-81.8,13.1,-78.3,-6.4C-74.8,-25.9,-64.1,-43.7,-49.9,-53.3C-35.7,-62.9,-17.8,-64.4,0.5,-65.1C18.9,-65.8,37.7,-65.8,45,-65.1Z' transform='translate(100 100)' /%3E%3C/svg%3E"),
    url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill='%23c2e0ff' fill-opacity='0.3' d='M43.8,-63.2C55.6,-53.1,63.2,-37.5,68.9,-20.6C74.6,-3.7,78.4,14.5,71.9,29.3C65.4,44.1,48.6,55.5,30.9,63.9C13.2,72.3,-5.4,77.7,-22.5,73.2C-39.6,68.7,-55.2,54.3,-64.5,36.8C-73.8,19.4,-76.8,-1.1,-71.5,-19.2C-66.2,-37.3,-52.6,-53.1,-36.8,-62.6C-21,-72.1,-3,-75.4,14.5,-86.6C32,-97.8,64.1,-116.9,77.3,-109.1C90.5,-101.3,84.8,-66.5,80.8,-37.8C76.8,-9.1,74.5,13.5,67.3,32.1C60.1,50.7,48,66.3,32.7,74.1C17.4,81.9,-1.1,81.9,-18.3,76.5C-35.5,71.1,-51.4,60.3,-61.9,45.4C-72.4,30.5,-77.5,11.5,-74.4,-6.2C-71.3,-23.9,-60,-40.4,-45.8,-50.2C-31.6,-60,-14.8,-63.1,2.1,-66.2C19,-69.3,37.9,-72.3,43.8,-63.2Z' transform='translate(100 100)' /%3E%3C/svg%3E"),
    linear-gradient(135deg, rgba(168, 208, 255, 0.2) 0%, rgba(255, 255, 255, 0.8) 100%);
  background-size: 300px 300px, 400px 400px, auto;
  animation: waveAnimation 20s linear infinite;
  z-index: -1;
}

@keyframes waveAnimation {
  0% {
    background-position: 0 0, 100px 100px, 0 0;
  }
  100% {
    background-position: 300px 300px, 500px 500px, 0 0;
  }
}

.profile-menu {
  background: transparent;
  border-right: none;
  height: 100%;
}

.profile-menu .el-menu-item {
  margin: 8px 12px;
  border-radius: 8px;
  height: 48px;
  line-height: 48px;
  transition: all 0.3s ease;
  background-color: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(5px);
}

.profile-menu .el-menu-item:hover {
  background-color: rgba(255, 255, 255, 0.9);
  transform: translateX(5px);
}

.profile-menu .el-menu-item.is-active {
  background-color: rgba(66, 135, 245, 0.15);
  color: #4287f5;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(66, 135, 245, 0.2);
}

/* 右侧内容区保持不变... */
.profile-content {
  background:
    url("data:image/svg+xml,%3Csvg width='600' height='600' viewBox='0 0 600 600' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cpath fill='%23d6e8ff' d='M300,0 C400,100 500,200 600,300 C500,400 400,500 300,600 C200,500 100,400 0,300 C100,200 200,100 300,0 Z'/%3E%3C/g%3E%3C/svg%3E"),
    linear-gradient(to bottom right, rgba(255, 255, 255, 0.95), rgba(245, 249, 255, 0.95));
  background-size: 800px 800px, auto;
  background-position: center;
  animation: watercolorRotate 60s linear infinite;
  border-radius: 12px;
  /* 其他样式保持不变 */
}

/* @keyframes watercolorRotate {
  0% { background-position: center; transform: rotate(0deg); }
  100% { background-position: center; transform: rotate(360deg); }
} */
</style>
